package com.mingzhi.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {

    //密钥过期的时间
    private static long Expiration = 30 * 60 * 1000;
    //用jwt生成一个随机对称密钥
    private static String secretString = "GDUskkcWo3AHd+Lpfk4qRnp5jYnrimHgvAbyLxMYQ/c=";
    //生成安全密钥
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
    public static String getJwt(Map<String,Object> claim){
        String token = Jwts.builder()
                .setClaims(claim)//自定义内容（负载）
                .signWith(key)//算法签名
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + Expiration))
                .compact();
        return token;
    }

    /**
     * 校验令牌
     */
    public static Claims verify(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            log.error("token过期，校验失败，token：" + token);
        }catch (Exception e){
            log.error("token校验失败，token：" + token);
        }
        return claims;
    }
}
